package com.share.device.emqx.callback;


import com.alibaba.fastjson2.JSONObject;
import com.share.device.emqx.ProtocolConvertUtil;
import com.share.device.emqx.factory.MessageHandlerFactory;
import com.share.device.emqx.handler.MessageHandler;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

//mqtt回调函数实现类
@Component
@Slf4j
public class OnMessageCallback implements MqttCallback {

    @Autowired
    private MessageHandlerFactory messageHandlerFactory;

    //断开连接回调
    @Override
    public void connectionLost(Throwable throwable) {
        // 连接丢失后，一般在这里面进行重连
        System.out.println("连接断开，可以做重连");
    }

    //当 MQTT 客户端接收到订阅的主题消息时触发。（订阅消息）
    @Override
    public void messageArrived(String topic, MqttMessage message) {
        System.out.println("接收消息主题:" + topic);
        System.out.println("接收消息Qos:" + message.getQos());
        System.out.println("接收消息内容:" + new String(message.getPayload()));

        try {
            // 根据topic选择不同的处理逻辑
            MessageHandler messageHandler = messageHandlerFactory.getMassageHandler(topic);
            if(messageHandler != null) {
                JSONObject jsonMessage = ProtocolConvertUtil.convertJson(new String(message.getPayload()));
                messageHandler.handleMessage(jsonMessage);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("mqtt消息异常：{}", new String(message.getPayload()));
        }
    }

    //当 MQTT 客户端成功将消息发送到 EMQX 服务器时触发。（发布消息）
    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        System.out.println("消息发送成功---------" + iMqttDeliveryToken.isComplete());
    }
}
